<?php
/*Array
(
    [status]       => 2
    [status_error] => Download error. Response code #404
    [url]          => http://xd-blog.com.ar/qwe
    [filePath]     => qwe
    [extra]        => array ("HD" => TRUE)
)
*/
while(1)
{
    echo "\n\nEnter command : ";
    $command = explode(" ",rtrim(fgets(STDIN)));
    switch($command[0])
    {
        case 'add':
            if( (sizeof($command)< 2) or ( (parse_url($command[1],PHP_URL_SCHEME)!=='http') and (parse_url($command[1],PHP_URL_SCHEME)!=='ftp') ) )
            {
                echo 'Use: add (http|ftp)://example.com/file.tar.gz [local-filename.tar.gz] [--HD]';
            }
            else
            {
                $extra = '';
                foreach ($command as $key => $thiscommand){
                    if(substr($thiscommand,0,2)=='--'){
                        $extra[substr($thiscommand,2)] = TRUE; 
                        unset($command[$key]);
                    }
                }
                $command = array_values($command);
                
                $url = $command[1];
                if(isset($command[2]))
                {
                    $filePath = str_replace('../', '', $command[2]);
                }
                else
                {
                    $filePath = call_user_func(pluginSelect($url).'_getName',$url);
                    $filePath = str_replace('../', '', $filePath);
                }
                shm_add ($shm_id, array (   'status'   => STATUS_WAIT,
                                            'url'      => $url,
                                            'filePath' => $filePath,
                                            'extra'    => $extra
                                        )
                         );
            }
        break;
        
        case 'list':
            $download_list = shm_get($shm_id);

            if (isset($command[1])) {
                if(isset($download_list[$command[1]])){
                    echo format_list($download_list[$command[1]], $command[1], true);
                } else {
                    echo 'Wrong ID'."\n";
                }
            } else {
                if(is_array($download_list)){
                    foreach ($download_list as $key => $download_file)
                    {
                        echo format_list($download_file, $key, false);
                    }
                }
                echo 'Total: '.(is_array($download_list)?sizeof($download_list):'0').' files.';
            }
        break;
        
        case 'cancel':
            $download_list = shm_get($shm_id);
            if (($command[1]=='') or !isset($command[1])){
                echo 'Use: cancel ID';
            }elseif(!isset($download_list[$command[1]])){
                echo 'ID doesn\'t exists';
            }elseif($download_list[$command[1]]['status'] == STATUS_CANCEL){
                echo 'Download already cancelled';
            }elseif($download_list[$command[1]]['status'] == STATUS_DOWNLOADED){
                echo 'Download already completed';
            }else{
                shm_update($shm_id, array ('status' => STATUS_CANCEL) , $command[1]) ;
            }
            
        break;
       
        case 'quit':
        case 'exit':
            shm_put($shm_id,'QUIT');
            if(pcntl_waitpid($pid, $status)<0) print($pid.' no finalizó correctamente');
            if (!shmop_delete($shm_id)) echo "Couldn't mark shared memory block for deletion."; //DEBUG
            shmop_close($shm_id);
            exit;
        break;
        
        case 'help':
            echo "Available commands: \n";
            echo "add (http|ftp)://example.com/file.tar.gz [local-filename.tar.gz] [--HD] \n";
            echo "list [ID] \n";
            echo "cancel ID \n";
            echo "quit \n";
            echo "help";
        break;
        
        default:
            echo 'Wrong command. Type "help" for more information';
        break;   
    }
}

function format_list($array, $id, $only_one = false)
{
    if (!$only_one) {
        /*
            [status] => 1
            [url] => http://xd-blog.com.ar/wargame/wargame1.jpg 40
            [filePath] => wargame1.jpg 40
            
        [#1234] wargame.jpg | http://xd-blog.com.ar/wargame/wargame1.jpg |Wait|
        [#1234] wargame.jpg | http://xd-blog.com.ar/wargame/wargame1.jpg |Wait|
        [#1234] wargame.jpg | http://xd-blog.com.ar/wargame/wargame1.jpg |Wait|
        
        */
        $salida = str_pad('#'.$id,4," ",STR_PAD_LEFT).' ';
        
        if (strlen($array['filePath'])>30) $array['filePath'] = "[...]".substr($array['filePath'],-25);
        $salida.= str_pad($array['filePath'],30," ",STR_PAD_LEFT).' | '; 
        
        if (strlen($array['url'])>40) $array['url'] = substr($array['url'],0,35)."[...]";
        $salida.= str_pad($array['url'],41," ",STR_PAD_RIGHT);
        
        if ($array['status'] == STATUS_WAIT) $salida.= '|   Waiting   |'; 
        elseif ($array['status'] == STATUS_DOWNLOADING) $salida.= '| Downloading |'; 
        elseif ($array['status'] == STATUS_DOWNLOADED) $salida.= '| Downloaded  |'; 
        elseif ($array['status'] == STATUS_ERROR) $salida.= '|    Error    |'; 
        elseif ($array['status'] == STATUS_CANCEL) $salida.= '|  Canceled   |'; 
        else $salida.= '|   Unknown   |'; 
        
        $salida.="\n";
        
        return $salida;
    } else {
        $salida = 'ID:        #'.$id."\n";
        $salida.= 'Save path: '.realpath('./files/').'/'.$array['filePath']."\n";
        $salida.= 'Url:       '.$array['url']."\n";
        
        $salida.= 'Status:    ';
        if ($array['status'] == STATUS_WAIT) $salida.= 'Waiting'; 
        elseif ($array['status'] == STATUS_DOWNLOADING) $salida.= 'Downloading'; 
        elseif ($array['status'] == STATUS_DOWNLOADED) $salida.= 'Downloaded'; 
        elseif ($array['status'] == STATUS_ERROR) $salida.= 'Error'; 
        elseif ($array['status'] == STATUS_CANCEL) $salida.= 'Canceled'; 
        else $salida.= 'Unknown'; 
        
        if (isset($array["status_error"])) $salida.= "\nError:     ".$array["status_error"];      
        if (isset($array['extra']) and ($array['extra'] != '')) $salida.= "\nExtra:     ".implode(' ',$array['extra']);         
    }
    
    $salida.="\n";

    return $salida;
}


?>